// 需求：连接数据库，实现登录验证
const express = require("express");
const server = express();
// 定义模板
const ejs = require("ejs");
server.set("views");
server.engine("html", ejs.renderFile);
// 导入中间件
const verify = require("./middleware/veify");
// 导入session模块
const session = require("express-session");
server.use(
  session({
    name: "_id",
    secret: "1208",
    saveUninitialized: false,
    resave: false,
    cookie: {
      httpOnly: false,
      maxAge: 1000 * 60 * 10,
    },
  })
);

// 导入数据库连接操作
const userModel = require("./database/model/userModel");
server.use(express.urlencoded({ extend: false }));

// 首页渲染
server.get("/", (req, res) => {
  // 获取登录之后的用户数据

  let { username } = req.session;
  console.log(username);
  res.render("index.html", { username: username });
});

// 登录页面渲染
server.get("/login", (req, res) => {
  res.render("login.html");
});

// 登录页面的数据提交
server.post("/login", (req, res) => {
  let { username, pwd } = req.body;
  console.log(userModel);
  userModel.find((err, data) => {
    // if (err) return err;
    let result = data.find((item) => {
      return item.username == username && item.pwd == pwd;
    });

    if (result) {
      req.session.username = username;
      res.render("loginSuccess.html");
      return;
    }
    res.send("登录失败");
  });
});

// 登录成功后跳转到个人中心页面
server.get("/center", verify, (req, res) => {
  let { username } = req.session;
  res.render("center.html", { name: username });
});

// 退出登录操作
server.get("/logout", verify, (req, res) => {
  req.session.destroy(() => {
    res.render("logoutSuccess.html");
  });
});

// 用户列表渲染
server.get("/userList", (req, res) => {
  userModel.find((err, data) => {
    res.render("userList.html", { data });
  });
});
// 删除操作
server.get("/deleteUsers/:id", (req, res) => {
  console.log(req.params);
  let { id } = req.params;
  userModel.deleteOne({ _id: id }, (err, data) => {
    console.log(data);
  });
  res.render("request.html", { data: "删除成功" });
});
// 修改操作
server.get("/updateUsers", (req, res) => {
  console.log(req.query);
  let { id } = req.query;
  // userModel.updateOne({_id:id},{})
  userModel.findById({ _id: id }, (err, data) => {
    res.render("update.html", { data });
  });
});
// 修改成功之后的提交操作
server.post("/updateUsers", (req, res) => {
  console.log(req.body, 1);
  let { username, pwd, _id } = req.body;
  userModel.updateOne({ _id }, { username, pwd }, (err, data) => {
    res.render("request.html", { data: "修改成功" });
  });
});

// 跳转到注册用户
server.get("/add", (req, res) => {
  res.render("add.html");
});
// 注册新的用户列表
server.post("/add", (req, res) => {
  console.log(req.body);
  let { username, pwd } = req.body;
  // 插入数据库
  userModel.create({ username, pwd }, (err, data) => {});
    res.render("request.html", { data: "注册成功" });

});
server.listen(80, () => {
  console.log("success");
});
